<template>
  <el-dialog :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1200px" @open="open" @close="close">
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit">
			<el-row>
				<el-col :span="12">
					<el-form-item label="区域名称" prop="areacode" :rules="rules.validateRequire">
						<el-select v-model="model.areacode" filterable clearable :disabled="areacodeDisabled">
							<el-option v-for="item in codeModel.areacodeList" :key="item.code" :label="item.name" :value="item.code" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="表名称" prop="tablename" >
						<el-input v-model="model.tablename" type="input" :rows="1" disabled></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="表字段" prop="fieldname" >
						<el-input v-model="model.fieldname" type="input" :rows="1"  disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="模块最大允许数" prop="maxnum" :rules="isMaxnum ? rules.validateIntGteZero1.concat(rules.validateRequire): []">
            <el-input-number v-model="model.maxnum" :step="1" :min="1" :max="60" :controls="false"  style="width:100%" @change="numberChange(arguments[0], 60)" :disabled="disabled" step-strictly></el-input-number>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="默认值" prop="defaultvalue" :rules="isdefaultValue ? rules.validateRequire : []">
            <def-Ref-List ref="defaultValueRef" v-model="model.extendfield2" dataType="code" :initDisplayData.sync="model.extendfield1" nameType="name" @confirm="saveApporFirstDirectory" queryDataUrl='/appv2/appAreaInitializationConfig/queryModule' :externalQueryParam="this.queryDataParam" :disabled="defaultValueForDisabled" :maxNum="parseInt (model.maxnum)"></def-Ref-List>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="是否发布" prop="publish" >
						<el-select v-model="model.publish" filterable clearable disabled>
							<el-option v-for="item in codeModel.publishList" :key="item.code" :label="item.name" :value="parseInt(item.code)" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="24">
					<el-form-item label="备注" prop="description" >
						<el-input v-model="model.description" type="textarea" :rows="4"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="有效" prop="enabled">
						<el-radio-group v-model="model.enabled">
							<el-radio :label="parseInt(item.code)" v-for="item in codeModel.enabledList" :key="item.code">{{ item.name }}</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
			</el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit">取消</el-button>
      <el-button type="primary" @click="doSaveEdit" :loading="saveLoading" v-if="disableEditSubmit === false">保存</el-button>
      <el-button type="primary"  v-if="this.model.publish === publishState.No && this.model.hasOwnProperty('id')" @click="doPublish">发布</el-button>
      <el-button type="primary"  v-if="showCoreBtn"  @click="changePosition(model.fieldname)">指定位置</el-button>
    </div>
    <change-module-position ref="changePositionRef"></change-module-position>
  </el-dialog>
</template>

<script>
/** mixins */
import { mixin_edit } from '@tapui/mixins/mixin_edit'
/** 子组件 */
import defRefList from './defRefList'
import changeModulePosition from './changeModulePosition'
/** 常量 */
import { AppUserUseInfo, AppAreaInitializationConfig, PublishState, AppAreaType } from '@/const/const'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { validateIntGteZero1 } from '@/utils/validateRule'
/** VUE配置 */
export default {
  mixins: [mixin_edit],
  components: { defRefList, changeModulePosition },
  data() {
    return {
      moduleTitle: '区域初始化配置',
      urlPrefix: '/appv2/appAreaInitializationConfig/',
      url: {
        // 额外的url
        dopublish: '/appv2/appAreaInitializationConfig/doPublish',
        select: '/appv2/appAreaInitializationConfig/selectAppORFirstDirectory',
        updateForceAppUserInfoCorearea: '/appv2/appAreaInitializationConfig/updateForceAppUserInfoCorearea',
        updateForceAppUserInfoCoreareaMaxnum: '/appv2/appAreaInitializationConfig/updateForceAppUserInfoCoreareaMaxnum',
        updateForceRecentlyMaxnum: '/appv2/appAreaInitializationConfig/updateForceAppUserInfoRecentlyusedareaMaxnum'
      },
      addRules: {
        validateIntGteZero1: [
          // 正整形校验
          { validator: validateIntGteZero1 }
        ]
      },
      // maxnum编辑控制状态
      disabled: false,
      //  发布状态
      publishLoading: false,
      queryDataParam: { flag: '0' },
      // 发布状态弹框状态
      dialogVisible: false,
      // 用户金刚区状态弹框状态
      dialogVisible1: false,
      // 用户金刚区最大数弹框状态
      dialogVisible2: false,
      // 用户最近访问最大数弹框状态
      dialogVisible3: false,
      // 用户一级目录状态弹框状态
      dialogVisible4: false,
      // 发布状态
      publishState: PublishState,
      // 维护区域
      appAreaInitializationConfig: AppAreaInitializationConfig,
      updateForceCoreareaLoading: false,
      updateForceCoreareaMaxnumLoading: false,
      updateForceRecentlyusedareaMaxnumLoading: false,
      updateForceFirstleveldirectoryLoading: false,
      // 默认值必填校验
      isdefaultValue: false,
      // 最大值必填校验
      isMaxnum: false,
      // 当前区域
      currentAreaname: '',
      // 当前区域最大数
      currentMaxnum: '',
      // 当前区域默认值
      currentDefaultvalue: ''
    }
  },
  methods: {
    // 修改位置
    changePosition(val) {
      if (val === AppUserUseInfo.corearea) {
        this.$refs.changePositionRef.changeType = AppAreaType.core
        this.$refs.changePositionRef.changeName = '金刚区'
        this.$refs.changePositionRef.maxPositionNum = parseInt(this.model.maxnum)
        this.$refs.changePositionRef.minPositionNum = 2
        this.$refs.changePositionRef.queryDataParam.flag = '1'
      } else if (val === AppUserUseInfo.firstleveldirectory) {
        this.$refs.changePositionRef.changeType = AppAreaType.firstlevel
        this.$refs.changePositionRef.changeName = '一级目录'
        this.$refs.changePositionRef.maxPositionNum = this.codeModel.firstDirectoryList.length
        this.$refs.changePositionRef.minPositionNum = 1
        this.$refs.changePositionRef.queryDataParam.flag = '0'
      } else if (val === AppUserUseInfo.extendfield1) {
        this.$refs.changePositionRef.changeType = AppAreaType.extendfield1
        this.$refs.changePositionRef.changeName = '文档中心'
        this.$refs.changePositionRef.maxPositionNum = this.codeModel.documentCenterList.length
        this.$refs.changePositionRef.minPositionNum = 1
        this.$refs.changePositionRef.queryDataParam.flag = '2'
      }
      this.$refs.changePositionRef.open()
    },
    loaded() {
      // 载入页面，记录当前默认值和最大数
      if (this.isAdd === false) {
         this.currentMaxnum = this.model.maxnum
         this.currentDefaultvalue = this.model.extendfield1
      }
      // 页面加载完毕执行。一级目录
      if (this.model.fieldname === 'firstleveldirectory') {
        this.$set(this.model, 'maxnum', undefined)
      }
      // 页面加载完毕执行。文档中心
      if (this.model.fieldname === 'extendfield1') {
        this.$set(this.model, 'maxnum', undefined)
      }
    },
      assignDefaultValue() {
      // 初始化发布状态
      this.$set(this.model, 'publish', 0)
    },
    // 发布操作
    doPublish() {
       this.$tap.confirm('是否确认发布？').then((_) => {
          // 表单校验
         this.$refs.form.validate((valid) => {
            if (valid) {
               // 修改发布状态
                this.$set(this.model, 'publish', 1)
                putAction(this.url.dopublish, this.model)
                    .then((res) => {
                      if (res.success) {
                          this.$message({
                              message: '发布成功！',
                              type: 'success'
                          })
                          this.visible = false
                          this.$emit('refresh')
                      } else {
                        this.$tap.alert(res.message, 'warning')
                      }
                    })
                    .catch((err) => {})
            } else {
              return false
            }
          })
          })
    },
    // 保存json格式数据
    saveApporFirstDirectory(selectedData) {
      var arr = []
      let i = 1
      // 当选中数据不为空时、遍历所选数据存入json
      if (selectedData.length > 0) {
         selectedData.forEach(item => {
           var str = {}
           str.code = item.code
           str.name = item.name
           str.sortcode = i
           i = i + 1
           arr.push(str)
      })
      var arr1 = JSON.stringify(arr)
      }
      // 当维护金刚区时，判断默认值中的app模块数量是否符合最大值的条件
      if (this.model.areacode === AppAreaInitializationConfig.corearea && this.model.maxnum) {
          if (selectedData.length <= parseInt(this.model.maxnum)) {
            // 符合条件
              this.model.defaultvalue = arr1
          } else {
             this.$tap.alert(`当前模块最大允许数为` + this.model.maxnum + '', 'warning')
            // 删掉所有已选项
            this.model.extendfield2 = ''
            this.model.extendfield1 = ''
          }
      } else {
          // 赋予最终处理值
          this.model.defaultvalue = arr1
      }
    },
    // 用户金刚区强制更新
    updateForceAppUserInfoCorearea() {
      this.$tap.confirm('是否确认强制更新用户金刚区？').then((_) => {
        // 表单校验
         this.$refs.form.validate((valid) => {
          if (valid) {
              putAction(this.url.updateForceAppUserInfoCorearea, this.model)
                  .then((res) => {
                    if (res.success) {
                        this.$message({
                            message: '强制更新成功！',
                            type: 'success'
                        })
                        this.$emit('refresh')
                        // this.visible = false
                    } else {
                      this.$tap.alert(res.message, 'warning')
                    }
                  })
                  .catch((err) => {})
           } else {
              return false
            }
          })
          })
    },
    // 用户金刚区最大数强制更新
    updateForceAppUserInfoCoreareaMaxnum() {
      this.$tap.confirm('是否确认强制更新用户金刚区最大数？').then((_) => {
           // 表单校验
         this.$refs.form.validate((valid) => {
          if (valid) {
              putAction(this.url.updateForceAppUserInfoCoreareaMaxnum, this.model)
                .then((res) => {
                  if (res.success) {
                      this.$message({
                          message: '强制更新成功！',
                          type: 'success'
                      })
                      this.visible = false
                      this.$emit('refresh')
                  } else {
                    this.$tap.alert(res.message, 'warning')
                  }
                })
              .catch((err) => {})
              } else {
                  return false
                }
              })
          })
    },
    // 二次确认的用户金刚区、金刚区最大数强制更新
    updateForceCoreareaMaxnumAndCorearea() {
      this.$tap.confirm('是否确认强制更新用户金刚区及最大数？').then((_) => {
           // 表单校验
         this.$refs.form.validate((valid) => {
          // 最大数
          if (valid) {
              putAction(this.url.updateForceAppUserInfoCoreareaMaxnum, this.model)
                .then((res) => {
                  if (res.success) {
                  } else {
                    this.$tap.alert(res.message, 'warning')
                  }
              })
              .catch((err) => {})
                } else {
                    return false
                  }
            // 默认值
            if (valid) {
              putAction(this.url.updateForceAppUserInfoCorearea, this.model)
                  .then((res) => {
                    if (res.success) {
                        this.$message({
                            message: '强制更新成功！',
                            type: 'success'
                        })
                        this.visible = false
                        this.$emit('refresh')
                        // this.visible = false
                    } else {
                      this.$tap.alert(res.message, 'warning')
                    }
                  })
                  .catch((err) => {})
           } else {
              return false
            }
          })
          })
    },
    // 用户最近使用最大数强制更新
    updateForceRecentlyMaxnum() {
       this.$tap.confirm('是否确认强制更新用户最近访问最大数？').then((_) => {
           // 表单校验
         this.$refs.form.validate((valid) => {
          if (valid) {
            putAction(this.url.updateForceRecentlyMaxnum, this.model)
              .then((res) => {
                if (res.success) {
                    this.$message({
                        message: '强制更新成功！',
                        type: 'success'
                    })
                    this.visible = false
                    this.$emit('refresh')
                } else {
                  this.$tap.alert(res.message, 'warning')
                }
              })
              .catch((err) => {})
           } else {
              return false
            }
          })
           })
    },
      /** 修改前执行 */
    dobeforeUpdate() {
      if (this.model.extendfield2 !== null && this.model.extendfield1 !== null) {
        // defaultNum 默认值编号
        var defaultNum6 = this.model.extendfield2.split(',')
        // defaultName 默认值名称
        var defaultName6 = this.model.extendfield1.split(',')
      }
      // 如果用户修改最大默认值数量，修改后的最大数小于现有默认值模块的总数，就削建当前默认值模块页面数量
      if (this.model.areacode === AppAreaInitializationConfig.corearea && this.model.maxnum) {
        if (defaultNum6.length >= parseInt(this.model.maxnum)) {
           var defaultNum7 = defaultNum6.slice(0, parseInt(this.model.maxnum))
           var defaultName7 = defaultName6.slice(0, parseInt(this.model.maxnum))
           var defaultNum8 = ''
           var defaultName8 = ''
           for (var i = 0; i < this.model.maxnum; i++) {
               defaultNum8 += defaultNum7[i] + ','
               defaultName8 += defaultName7[i] + ','
           }
            this.model.extendfield2 = defaultNum8.substring(0, defaultNum8.length - 1)
            this.model.extendfield1 = defaultName8.substring(0, defaultName8.length - 1)
        }
      }
    },
    /** 执行编辑提交 */
    doEdit() {
      this.saveLoading = true
      putAction(this.url.edit, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message(res.message, 'success')
            this.visible = false
            this.$emit('refresh')
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
      numberChange(val, maxNum) {
      if (this.model.extendfield2 !== null && this.model.extendfield1 !== null && this.model.extendfield2 !== undefined && this.model.extendfield1 !== undefined) {
        // 默认值编号 defaultNum
        var defaultNum3 = this.model.extendfield2.split(',')
        // 默认值名称 defaultName
        var defaultName3 = this.model.extendfield1.split(',')
      }
      if (val !== '' && this.model.extendfield2 !== undefined && this.model.extendfield1 !== undefined && this.model.extendfield2 !== null && this.model.extendfield1 !== null && this.model.defaultvalue !== '' && this.model.defaultvalue !== undefined) {
        var defaultvalue1 = JSON.parse(this.model.defaultvalue)
        var arr2 = []
        if (parseInt(Number(val)) < defaultNum3.length) {
           var defaultNum4 = defaultNum3.slice(0, parseInt(this.model.maxnum))
           var defaultName4 = defaultName3.slice(0, parseInt(this.model.maxnum))
           var defaultNum5 = ''
           var defaultName5 = ''
           for (var i = 0; i < this.model.maxnum; i++) {
               arr2.push(defaultvalue1[i])
               defaultNum5 += defaultNum4[i] + ','
               defaultName5 += defaultName4[i] + ','
           }
            this.model.extendfield2 = defaultNum5.substring(0, defaultNum5.length - 1)
            this.model.extendfield1 = defaultName5.substring(0, defaultName5.length - 1)
            var arr3 = JSON.stringify(arr2)
            // 如果数值为空，就赋空值
            if (this.model.maxnum === 0) {
             this.model.defaultvalue = ''
            } else {
             this.model.defaultvalue = arr3
      }
        }
      }
    },
    /** 保存确认 */
    doSaveEdit() {
      if (!this.beforeSubmit()) {
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            this.doAdd()
          } else {
            // 当前选择区域是最近使用区域时
            if (this.model.publish === PublishState.Yes && this.model.areacode === AppAreaInitializationConfig.recentlyusedarea) {
                // 比较最近使用最大数表格值与填写的默认值,如果不同则触发是否更新
                if (parseInt(this.currentMaxnum) !== parseInt(this.model.maxnum)) {
                    this.updateForceRecentlyMaxnum()
                } else {
                  // 执行保存操作
                    this.doEdit()
                }
              // 当前选择区域是金刚区区域时
             } else if (this.model.publish === PublishState.Yes && this.model.areacode === AppAreaInitializationConfig.corearea) {
                 // 比较金刚区默认值最大数表格值与填写的默认值,如果不同则触发是否更新
                 // 只有最大数有改变
                if ((parseInt(this.currentMaxnum) !== parseInt(this.model.maxnum)) && (this.currentDefaultvalue === this.model.extendfield1)) {
                    this.updateForceAppUserInfoCoreareaMaxnum()
                 // 只有默认值有变化
                } else if ((parseInt(this.currentMaxnum) === parseInt(this.model.maxnum)) && (this.currentDefaultvalue !== this.model.extendfield1)) {
                    this.updateForceAppUserInfoCorearea()
                    // 默认值和最大数都变化
                } else if ((parseInt(this.currentMaxnum) !== parseInt(this.model.maxnum)) && (this.currentDefaultvalue !== this.model.extendfield1)) {
                    this.updateForceCoreareaMaxnumAndCorearea()
                } else {
                    // 执行保存操作
                    this.doEdit()
                }
                // 当前选择区域是一级目录时
             } else {
                  // 执行保存操作
                  this.doEdit()
             }
          }
        } else {
          return false
        }
      })
    }
  },
  watch: {
	// 监听areacode，遍历编码值并把值赋给model中的areaname
  // 用户在选维护的区域时，自动带入用户信息表对应的维护字段
		'model.areacode'(newVal, oldVal) {
      if (newVal !== '') {
        // 每次新增切换如果默认值或最大值有值，就将默认值和最大值清空
        if (this.model.maxnum !== '' && this.model.maxnum !== undefined && this.isAdd === true) {
           this.$set(this.model, 'maxnum', undefined)
        }
        if (this.model.extendfield2 !== '' && this.model.extendfield2 !== undefined && this.isAdd === true) {
           this.model.extendfield2 = ''
        }
        if (this.model.extendfield1 !== '' && this.model.extendfield1 !== undefined && this.isAdd === true) {
           this.model.extendfield1 = ''
        }
        if (this.model.defaultvalue !== '' && this.model.defaultvalue !== undefined && this.isAdd === true) {
           this.model.defaultvalue = ''
        }
        // 每次切换前，将可编辑状态恢复初始情况
       this.disabled = false
       this.isdefaultValue = false
       this.isMaxnum = false
       // 每次切换表名称都赋初值
       this.$set(this.model, 'tablename', 'AppUserUseInfo')
      //  this.disabled1 = false
       switch (newVal) {
              // 金刚区
            case AppAreaInitializationConfig.corearea:
              // 初始金刚区默认值不可用
              this.model.fieldname = AppUserUseInfo.corearea
              this.queryDataParam.flag = '1'
              this.isdefaultValue = true
              this.isMaxnum = true
              break
              // 最近使用模块
            case AppAreaInitializationConfig.recentlyusedarea:
              this.model.fieldname = AppUserUseInfo.recentlyusedarea
              this.queryDataParam.flag = '1'
              this.isMaxnum = true
              // 默认值不可用
              break
              // 一级目录排序
            case AppAreaInitializationConfig.firstleveldirectory:
              this.model.fieldname = AppUserUseInfo.firstleveldirectory
              this.queryDataParam.flag = '0'
              // 最大数不可用
              this.disabled = true
              this.isdefaultValue = true
              break
              // 文档中心
            case AppAreaInitializationConfig.extendfield1:
              this.model.fieldname = AppUserUseInfo.extendfield1
              this.queryDataParam.flag = '2'
              // 最大数不可用
              this.disabled = true
              this.isdefaultValue = true
              break
        }
      this.codeModel.areacodeList.forEach(item => {
        if (item.code === newVal) {
           this.model.areaname = item.name
        }
      })
      } else {
        // 清空区域，就清空所有页面值
        this.model.fieldname = ''
        this.model.tablename = ''
        this.model.areaname = ''
        this.model.maxnum = null
        this.model.extendfield2 = ''
        this.model.extendfield1 = ''
        this.model.defaultvalue = ''
      }
    }
   },
   computed: {
    showCoreBtn() {
      if (this.model.publish === this.publishState.Yes && (this.model.areacode === AppAreaType.core || this.model.areacode === AppAreaType.firstlevel || this.model.areacode === AppAreaType.extendfield1) && this.isAdd === false && this.disableEditSubmit === false) {
        return true
      } else {
        return false
      }
    },
    // 默认值计算属性
     defaultValueForDisabled() {
      // 选择区域为空时
      if (!this.model.areacode) {
          return true
      } else if (this.disableEditSubmit) {
         return true
      // 最近使用不允许没有默认值
      } else if (this.model.areacode === AppAreaInitializationConfig.recentlyusedarea) {
          return true
       // 第一目录排序
      } else if (this.model.areacode === AppAreaInitializationConfig.firstleveldirectory) {
        return false
        // 金刚区且最大值有值
      } else if (this.model.areacode === AppAreaInitializationConfig.corearea && this.model.maxnum) {
        return false
        // 文档中心
      } else if (this.model.areacode === AppAreaInitializationConfig.extendfield1) {
        return false
      } else {
        return true
      }
     },
     // 发布区域控制状态
     areacodeDisabled() {
       if (this.model.publish === PublishState.Yes || this.isAdd === false) {
         return true
       } else {
         return false
       }
     }
   }
}
</script>
<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
input[type=“number”]{
-moz-appearance: textfield;
}

.el-input-number.is-without-controls .el-input__inner {
  width: 430px;
}
</style>

